package com.heima.service.impl;

import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.domain.Patient;
import com.heima.domain.Users;
import com.heima.domain.UsersAccount;
import com.heima.dto.UserDto;
import com.heima.mapper.PatientMapper;
import com.heima.mapper.UsersAccountMapper;
import com.heima.mapper.UsersMapper;
import com.heima.service.IUsersService;
import com.heima.vo.LoginOpenidVO;
import com.heima.vo.RegisterVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 小程序用户 服务实现类
 * </p>
 *
 * @author wangjiexin
 * @since 2023-01-29
 */
@Service
@Slf4j
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {
    @Autowired
    UsersMapper usersMapper;
    @Autowired
    UsersAccountMapper usersAccountMapper;
    @Autowired
    PatientMapper patientMapper;

    @Override
    public LoginOpenidVO getOpenId(String code) {

        //判空一下
        //isEmpty 代表 变量存在，但是值为空
        //isBlank 代表 变量不存在

        if (StringUtils.isEmpty(code)){
            throw new RuntimeException("入参不能为空");
        }

        //微信调用的接口GET http://localhost:9090/sns/jscode2session
        //调用别的服务的时候用的是RestTemplate这个东西
        RestTemplate restTemplate=new RestTemplate();
        //设置一下调用微信端口的url
        String url="http://localhost:9090/sns/jscode2session";
        url+="?appid=wxe6f0c12631e361d0";
        url+="&secret=6cb71ccff4a8bb85c153ad6ec996855c";
        url+="&js_code="+code;
        url+="&grant_type=authorization_code";
            //因为微信接口是get请求的 所以这边要写get开头的请求路径
        Map res = restTemplate.getForObject(url,Map.class);

        //取id和错误码
        Object openid = res.get("openid");

        //返回前端
        LoginOpenidVO vo=new LoginOpenidVO();
        vo.setOpenId((String) openid);

        return vo;
    }

    @Override
    public RegisterVO register(UserDto dto) {
        Map<String,Object> payload=new HashMap<>();
        //入参判空
        if (dto==null){
            log.error("报错了");
            throw new RuntimeException("入参不能为空~！");
        }
        //检查 openid和phone是否存在于数据库中
        LambdaQueryWrapper<Users> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Users::getOpenId, dto.getOpenId());
        wrapper.eq(Users::getPhone, dto.getPhone());
        Users resUser = usersMapper.selectOne(wrapper);
        //不存在
            if (resUser==null){
                //不存在就给他写进去一个
                Users user=new Users();
                BeanUtils.copyProperties(dto, user);
                user.setAvatar(dto.getAvatarUrl());
                user.setNickname(dto.getNickName());
                int add = usersMapper.insert(user);
                if (add!=1){
                    throw new RuntimeException("插入用户表数据异常~！");
                }
                UsersAccount account=new UsersAccount();
                account.setUserId(user.getId());
                //设置账户
                //设置默认的金钱为0
                account.setBalance(0);
                int acc = usersAccountMapper.insert(account);
                if (acc!=1){
                    throw new RuntimeException("账户插入失败~！！");
                }
                //设置默认就诊人信息
                Patient patient=new Patient();
                patient.setUserId(user.getId());
                patient.setName(dto.getNickName());
                patient.setTags("本人");
                patient.setPhone(dto.getPhone());
                patient.setAddress(dto.getCountry()+""+dto.getProvince()+""+dto.getCity());
                patient.setIsDefault(0);
                int insert = patientMapper.insert(patient);
                if (insert!=1){
                    throw new RuntimeException("插入就诊人信息失败~！！！");
                }

                payload.put("id", user.getId());
                payload.put("openId",user.getOpenId());

            }  else {
                Users user=new Users();
                payload.put("id", user.getId());
                payload.put("openId",user.getOpenId());
            }
         //存在
        //这边做一个token的生成，并返回给前端
        //用糊涂的工具 生成jwt 的token
        //一共三个东西-- 头部、载荷、签名

        String token = JWTUtil.createToken(null, null, "heima".getBytes());
        //把生成的token写进去，然后返回给前端
        RegisterVO vo=new RegisterVO();
        vo.setToken(token);
        return vo;
    }
}
